package com.grj.order.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.grj.common.model.Order;
import com.grj.common.model.OrderOutbox;
import com.grj.order.repository.OrderRepository;
import com.grj.order.repository.OutboxRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ganru
 * @date 2025/10/19 5:47
 */
@Service
public class OrderWriteService {
    private final OrderRepository orderRepository;
    private final OutboxRepository outboxRepository;
    private final ObjectMapper objectMapper;

    public OrderWriteService(OrderRepository orderRepository, OutboxRepository outboxRepository, ObjectMapper objectMapper) {
        this.orderRepository = orderRepository;
        this.outboxRepository = outboxRepository;
        this.objectMapper = objectMapper;
    }

    @Transactional
    public Order createOrder(Order order) {
        orderRepository.save(order);

        try {
            OrderOutbox out = new OrderOutbox();
            out.setAggregateType("Order");
            out.setAggregateId(order.getOrderId());
            out.setEventType("order-created");
            out.setPayload(objectMapper.writeValueAsString(order));
            outboxRepository.save(out);
        } catch (Exception e) {
            throw new RuntimeException("序列化出错", e);
        }

        return order;
    }
}